<!-- 宠物门店信息配置 -->
<template>
    <div >
        <div class='table-page-search-wrapper'>
            <a-form layout='inline'>
               <a-row :gutter='48'>
                    <a-col :md='8' :sm='24'>
                        <a-form-item label="店铺名称">
                            <a-input v-model="storeName" allow-clear placeholder="请输入店铺名称" />
                        </a-form-item>
                    </a-col>
                    <a-col :md='8' :sm='24'>
                        <a-form-item label="商家姓名">
                            <a-input v-model="fullName" allow-clear placeholder="请输入商家姓名" />
                        </a-form-item>
                    </a-col>
                    <a-col :md='8' :sm='24'>
                        <a-form-item label="用户ID">
                            <a-input v-model="userId" allow-clear placeholder="请输入用户ID" />
                        </a-form-item>
                    </a-col>
                    <a-col :md='8' :sm='24'>
                        <a-form-item label="手机号">
                            <a-input v-model="phone" allow-clear placeholder="请输入手机号" />
                        </a-form-item>
                    </a-col>
                    <a-col :md='8' :sm='24'>
                        <a-form-item label="省份">
                            <a-input v-model="province" allow-clear placeholder="请输入省份" />
                        </a-form-item>
                    </a-col>
                    <a-col :md='8' :sm='24'>
                        <a-form-item label="城市">
                            <a-input v-model="city" allow-clear placeholder="请输入城市" />
                        </a-form-item>
                    </a-col>
                    <a-col :md='8' :sm='24'>
                        <a-form-item label="区域">
                            <a-input v-model="area" allow-clear placeholder="请输入区域" />
                        </a-form-item>
                    </a-col>
                    <a-col :md='8' :sm='24'>
                        <a-form-item label="城镇">
                            <a-input v-model="town" allow-clear placeholder="请输入城镇" />
                        </a-form-item>
                    </a-col>
                    <a-col :md='8' :sm='24'>
                        <a-form-item label="状态">
                            <a-select v-model="status" placeholder="请选择" allowClear @change="getData">
                                <a-select-option v-for="(item,i) in statusList" :key="i" :value="item.id">{{item.name}}</a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :md='8' :sm='24'>
                        <a-form-item >
                            <a-button type='primary' style="margin-right: 20px" @click="getData">查询</a-button>
                            <a-button type="" icon="plus" @click="add()">添加</a-button>
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-form>
        </div>  

        <a-table rowKey="id" :loading="isload" :columns="columns" :data-source="dataList" @change="handleTableChange" :pagination="{ pageSize: 10, total: total ,showSizeChanger: true,pageSize: size, }" size="small" :scroll="{ x: 1400, }">
            <div slot="serviceProjectId" slot-scope="serviceProjectId">
                <span v-for="spec in serviceProjectId.split(',')" :key="spec">
                    <span v-for="(item,i) in projectList" :key="item.id">
                        <a-tag v-if="item.id == spec" :color="colors[i%13]">{{item.name}}</a-tag>
                    </span>
                </span>
            </div>
            <div slot="logoUrl" slot-scope="logoUrl">
                <img style="width: 120px;height: 60px" v-if="logoUrl && logoUrl.substring(0,4) == 'http'" :src="logoUrl && logoUrl.split(',')[0]" alt="" @click="showImg(logoUrl)">
                <div v-else>-</div>
            </div>
            <template slot="province" slot-scope="province, record">
                <a-tag :color="colors[2]">{{province}}-{{record.city}}-{{record.area}}-{{record.town}}</a-tag>
            </template>
            <div slot="detailedAddress" slot-scope="detailedAddress">
                <ellipsis :length="18" tooltip>{{ detailedAddress == '' || !detailedAddress ? '-' : detailedAddress }}</ellipsis>
            </div>
            <div slot="status" slot-scope="status">
                <a-switch checked-children="开" un-checked-children="关" disabled :checked="status == 1 ? true : false" />
            </div>
            <div slot="operation" slot-scope="text,record">
                <a-button type="link" @click="update(record)">修改</a-button>
                <a-popconfirm
                    title="是否确认删除当前配置?"
                    ok-text="Yes"
                    cancel-text="No"
                    @confirm="del(record)"
                >
                    <a-button class="errorColor" type="link">删除</a-button>
                </a-popconfirm>
            </div>
        </a-table>

        <a-modal
            title="添加、修改商家信息"
            :visible="visible"
            @ok="handleOk"
            :confirm-loading="confirmLoading"
            @cancel="visible = false"
            >
            <div>
                <a-form :label-col="{ span: 8 }" :wrapper-col="{ span: 14 }">
                    <a-form-item label="用户ID">
                        <a-input v-model="item.userId" placeholder="请输入用户ID" allow-clear></a-input>
                    </a-form-item>
                    <a-form-item label="店铺名称">
                        <a-input v-model="item.storeName" placeholder="请输入店铺名称" allow-clear></a-input>
                    </a-form-item>
                    <a-form-item label="商家姓名">
                        <a-input v-model="item.fullName" placeholder="请输入商家姓名" allow-clear></a-input>
                    </a-form-item>
                    <a-form-item label="商家身份证号">
                        <a-input v-model="item.idCard" placeholder="请输入商家身份证号" allow-clear></a-input>
                    </a-form-item>
                    <a-form-item label="商家电话">
                        <a-input v-model="item.phone" placeholder="请输入商家电话" allow-clear></a-input>
                    </a-form-item>
                    <a-form-item label="地区">
                        <a-cascader v-model="defaultValue" :options="options" :fieldNames="{label: 'areaName','value': 'areaName',children: 'children'}"  :load-data="loadData" change-on-select placeholder="请选择地区" />
                    </a-form-item>
                    <a-form-item label="详细地址" >
                        <a-textarea v-model="item.detailedAddress" placeholder="请输入详细地址" :auto-size="{ minRows: 2, maxRows: 5 }" allow-clear/>
                    </a-form-item>
                    <a-form-item label="商铺LOGO">
                        <div class="clearfix">
                            <a-upload
                                list-type="picture-card"
                                accept="image/*"
                                :file-list="imgList"
                                @preview="handlePreview"
                                @change="imgHandleChange"
                                :before-upload="beforeUpload"
                            >
                                <div v-if="imgList.length < 1">
                                    <a-icon type="plus" />
                                    <div class="ant-upload-text">选择商铺LOGO图片</div>
                                </div>
                            </a-upload>
                        </div>
                    </a-form-item>
                    <a-form-item label="营业执照图片">
                        <div class="clearfix">
                            <a-upload
                                list-type="picture-card"
                                accept="image/*"
                                :file-list="imgList1"
                                @preview="handlePreview"
                                @change="imgHandleChange1"
                                :before-upload="beforeUpload"
                            >
                                <div v-if="imgList1.length < 1">
                                    <a-icon type="plus" />
                                    <div class="ant-upload-text">选择上传营业执照图片</div>
                                </div>
                            </a-upload>
                        </div>
                    </a-form-item>
                    <a-form-item label="状态">
                        <a-radio-group v-model="item.status" >
                            <a-radio  v-for="(item,i) in statusList" :key="i" :value="item.id">{{item.name}}</a-radio>
                        </a-radio-group>
                    </a-form-item>
                </a-form>
            </div>
        </a-modal>

        <!-- 上传图片预览 -->
        <a-modal :visible="previewVisible" :footer="null" @cancel="previewVisible = false">
            <img alt="example" style="width: 100%" :src="previewImage" />
        </a-modal>
        <!-- 表格图片预览 -->
        <a-modal :visible="previewImgVisible" :footer="null" @cancel="previewImgVisible = false">
            <a-carousel autoplay dots-class="slick-dots slick-thumb" arrows style="margin-bottom:60px">
                <div v-for="(img,i) in showImgs" :key="i">
                    <img :src="img" alt=""/>
                </div>
                <a slot="customPaging" slot-scope="props">
                    <img :src="getImgUrl(props.i)" />
                </a>
            </a-carousel>
        </a-modal>
    </div>
</template>

<script>
import { queryGoodsMerchantInfo , updateGoodsMerchantInfo } from '@/api/newMall';
import { columns } from './table';
import { uploadFile , queryAreaInfo , queryTencentAddressResolution , identficationAddress } from '@/api/brand';
import { Ellipsis } from '@/components';
export default {
    components: {
        Ellipsis,
    },
    data () {
        return {
            brandId: this.global.brandId,
            storeName: '', // 店铺名称
            fullName: '', // 商家姓名
            phone: '', // 手机号
            userId: '', // 用户ID
            serviceProjectId: undefined, // 服务ID
            projectList: [], // 服务列表
            province: '',
            city: '',
            area: '',
            town: '', // 城镇
            status: undefined, // 状态
            statusList: [
                { id: '1', name: '开启'},
                { id: '0', name: '关闭'},
            ],
            columns,
            dataList: [],
            total: 0,
            isload: false,
            page: 1,
            size: 10,
            colors: ['blue','purple','cyan','green','orange','red','pink','brown','indigo','lime','purple','teal','yellow','amber'],
            item: {
                id: '',
                userId: '',
                fullName: '',
                storeName: '',
                idCard: '',
                phone: '', // 电话
                businessLicenseUrl: '', // 营业执照图片地址
                logoUrl: '', // LOGO图片地址
                province: '', // 省份
                city: '', // 城市
                area: '', // 地区
                town: '', // 城镇
                detailedAddress: '', //  详细地址
                longitude: '', // 经度
                latitude: '', // 维度
                status: '1',
            },
            confirmLoading: false,
            isAdd: true,
            visible: false,
            imgList: [],
            previewVisible: false,
            previewImage: '',
            previewImgVisible: false,
            showImgs: [],
            imgList: [],
            imgList1: [], // 营业执照
            provinces: '',
            citys: '',
            areas: '',
            provinceList: [],
            cityList: [],
            areaList: [],
            townList: [],
            options: [], // 地区 筛选
            defaultValue: [],
        };
    },
    async created(){
        try {
            // await this.queryProject();
            this.provinceList = await this._queryAreaInfo('0');
            this.options = this.provinceList;
            console.log(this.options,'options')
            this.getData()
        } catch (error) {
            this.$notification['error']({
                message: '提示',
                description: error,
                duration: 8,
            })
        }
    },
    methods: {
        // 查询数据
        getData(){
            let _this = this
            _this.isload = true
            const params = {
                'brandId': _this.global.brandId,
                'storeName': _this.storeName,
                'fullName': _this.fullName,
                'phone': _this.phone,
                'userId': _this.userId,
                'province': _this.province,
                'city': _this.city,
                'area': _this.area,
                'town': _this.town,
                'status': _this.status,
                'size':_this.size,
                'page':_this.page - 1,
            }
            queryGoodsMerchantInfo(params)
            .then(res=>{
                _this.isload = false
                if(res.success){
                    _this.dataList = res.data.content
                    _this.total = res.data.totalElements
                }else{
                    _this.$notification['error']({
                        message: '提示',
                        description: res.errMessage,
                        duration: 8,
                    })
                }
            })
        },
        // 分页
        handleTableChange(pagination, filters, sorter) {
            console.log(pagination);
            this.page = pagination.current;
            this.size = pagination.pageSize;
            this.getData()
        },
        // 添加
        add(){
            this.isAdd = true;
            this.item.id = '';
            this.item.userId = '';
            this.item.phone = '';
            this.item.fullName = '';
            this.item.storeName = '';
            this.item.idCard = '';
            this.item.businessLicenseUrl = '';
            this.item.logoUrl = '';
            this.item.province = '';
            this.item.city = '';
            this.item.area = '';
            this.item.town = '';
            this.item.detailedAddress = '';
            this.item.longitude = '';
            this.item.latitude = '';
            this.defaultValue = [];
            this.item.status = '1';
            this.imgList = [];
            this.visible = true
        },
        // 修改
        async update(item){
            let _this = this;
            _this.item = JSON.parse(JSON.stringify(item))
            _this.defaultValue = [item.province,item.city,item.area,item.town];
            var province = _this.options.find(itm => itm.areaName == item.province);
            var selOption = [province];
            await _this.loadData(selOption);
            for (let index = 1; index < _this.defaultValue.length - 1; index++) {
                const element = _this.defaultValue[index];
                var list = [];
                if(index == 1){
                    list = _this.cityList;
                }
                if(index == 2){
                    list = _this.areaList;
                }
                var area = list.find(itm => itm.areaName == element);
                selOption.push(area);
                await _this.loadData(selOption);
            }
            _this.imgList = [];
            _this.imgList1 = [];
            if(item.logoUrl && item.logoUrl.substring(0,4) == 'http'){
                var array = item.logoUrl.split(',');
                let _this = this;
                for (let index = 0; index < array.length; index++) {
                    const element = array[index];
                    _this.imgList.push({
                        'uid': index +1,
                        'id': index +1,
                        'url': element,
                        'status':'done',
                        'name':element,
                        'noFile': true,
                    })
                }
            }
            if(item.businessLicenseUrl && item.businessLicenseUrl.substring(0,4) == 'http'){
                var array = item.businessLicenseUrl.split(',');
                let _this = this;
                for (let index = 0; index < array.length; index++) {
                    const element = array[index];
                    _this.imgList1.push({
                        'uid': index +1,
                        'id': index +1,
                        'url': element,
                        'status':'done',
                        'name':element,
                        'noFile': true,
                    })
                }
            }
            this.isAdd = false;
            this.visible = true
        },
        // 确认添加、修改
        async handleOk(){
            let _this = this
            console.log(_this.defaultValue,'defaultvalue')
            if(_this.item.userId == ''){
                _this.$message.warning('请输入用户ID')
                return;
            }
            if(_this.item.storeName == ''){
                _this.$message.warning('请输入店铺名称')
                return;
            }
            if(_this.item.fullName == ''){
                _this.$message.warning('请输入商家姓名')
                return;
            }
            if(_this.item.idCard == ''){
                _this.$message.warning('请输入商家身份证号')
                return;
            }
            if(_this.item.phone == ''){
                _this.$message.warning('请输入商家联系电话')
                return;
            }
            if(_this.defaultValue.length != 4){
                _this.$message.warning('请选择商家所在地区')
                return;
            }
            if(_this.item.detailedAddress == ''){
                _this.$message.warning('请输入商家详细地址')
                return;
            }
            var imgList = [];
            var imgList1 = [];
            if(_this.imgList.length > 0){
                for (let index = 0; index < _this.imgList.length; index++) {
                    const element = _this.imgList[index];
                    if(element.noFile){
                        imgList.push(element.url);
                    }else{
                        try {
                            var imgs = await _this.uploadImg(element.originFileObj,`logo${index}`);
                            console.log(imgs,'imgs');
                            imgList.push(imgs);
                        } catch (error) {
                            _this.$notification['error']({
                                message: '提示',
                                description: error,
                                duration: 8,
                            })
                            return;
                        }
                    }
                }
                _this.item.logoUrl = imgList.join(',');
            }
            if(_this.imgList1.length > 0){
                for (let index = 0; index < _this.imgList1.length; index++) {
                    const element = _this.imgList1[index];
                    if(element.noFile){
                        imgList1.push(element.url);
                    }else{
                        try {
                            var imgs = await _this.uploadImg(element.originFileObj,`businessLicenseUrl${index}`);
                            console.log(imgs,'imgs');
                            imgList1.push(imgs);
                        } catch (error) {
                            _this.$notification['error']({
                                message: '提示',
                                description: error,
                                duration: 8,
                            })
                            return;
                        }
                    }
                }
                _this.item.businessLicenseUrl = imgList1.join(',');
            }
            try {
                var address = await _this._identficationAddress();
                console.log(address,'address')
                _this.item.longitude = address.longitude;
                _this.item.latitude = address.latitude;
            } catch (error) {
                console.log(error,'error')
                _this.$notification['error']({
                    message: '提示',
                    description: error,
                    duration: 8,
                })
                return;
            }
            const params = {
                'id': _this.item.id,
                'userId': _this.item.userId,
                'fullName': _this.item.fullName,
                'storeName': _this.item.storeName,
                'idCard': _this.item.idCard,
                'logoUrl': _this.item.logoUrl,
                'businessLicenseUrl': _this.item.businessLicenseUrl,
                'phone': _this.item.phone,
                'province': _this.defaultValue[0],
                'city': _this.defaultValue[1],
                'area': _this.defaultValue[2],
                'town': _this.defaultValue[3],
                'detailedAddress': _this.item.detailedAddress,
                'longitude': _this.item.longitude,
                'latitude': _this.item.latitude,
                'status': _this.item.status,
                'brandId': _this.brandId,
            }
            updateGoodsMerchantInfo(params)
            .then(res=>{
                if(res.success){
                    _this.visible = false;
                    _this.getData();
                    _this.$notification['success']({
                        message: '提示',
                        description: _this.isAdd ? '添加成功' : '修改成功',
                        duration: 8,
                    })
                }else{
                    _this.$notification['error']({
                        message: '提示',
                        description: res.errMessage,
                        duration: 8,
                    })
                }
            })
        },
        // 删除
        del(item){
            let _this = this
            const params = {
                'id': item.id,
                'name': item.name,
                'isDelete': '1'
            }
            updateGoodsMerchantInfo(params)
            .then(res=>{
                if(res.success){
                    _this.getData();
                    _this.$notification['success']({
                        message: '提示',
                        description: '删除成功',
                        duration: 8,
                    })
                }else{
                    _this.$notification['error']({
                        message: '提示',
                        description: res.errMessage,
                        duration: 8,
                    })
                }
            })
        },
        // 预览图片
        showImg(imgs){
            if(imgs){
                this.showImgs = imgs.split(',')
                console.log(this.showImgs,'imgs')
                this.previewImgVisible = true
            }
        },
        getImgUrl(i){
            return this.showImgs[i]
        },
        async handlePreview(file) {
            if (!file.url && !file.preview) {
                file.preview = await getBase64(file.originFileObj);
            }
            this.previewImage = file.url || file.preview;
            this.previewVisible = true;
        },
        imgHandleChange({ fileList }) {
            this.imgList = fileList;
        },
        imgHandleChange1({ fileList }) {
            this.imgList1 = fileList;
        },
        beforeUpload(file) {
            return false;
        },
        // 上传图片获取图片url
        uploadImg(file,name){
            let _this = this
            return new Promise((resolve,reject) => {
                let formData = new FormData()
                formData.append('brandId',_this.brandId)
                formData.append('urlName',name)
                formData.append('file',file)
                uploadFile(formData)
                .then(res=>{
                    if(res.success){
                        resolve(res.data)
                    }else{
                        reject(res.errMessage);
                    }
                })
            })
        },
        // 解析地址
        _identficationAddress(){
            var address = `${this.item.province}${this.item.city}${this.item.area}${this.item.town}${this.item.detailedAddress}`;
            return new Promise((resolve,reject) => {
                queryTencentAddressResolution({
                    detailedAddress: this.item.detailedAddress,
                    province: this.defaultValue[0],
                    city: this.defaultValue[1],
                    area: this.defaultValue[2],
                    town: this.defaultValue[3],
                })
                .then(res => {
                    console.log(res,'地址res')
                    if(res.success){
                        resolve(res.data);
                    }else{
                        reject(res.errMessage)
                    }
                })
            })
        },
        // 获取省市区
        async _queryAreaInfo(areaParentId){
            return new Promise((resolve,reject) => {
                queryAreaInfo(areaParentId)
                .then(res => {
                    if(res.success){
                        var list = [];
                        for (let index = 0; index < res.data.length; index++) {
                            const element = res.data[index];
                            if(areaParentId.length != 6 || (areaParentId.length == 6 && areaParentId.substring(4) == '00')){
                                element.isLeaf = false;
                            }
                            list.push(element);
                        }
                        resolve(list)
                    }else{
                        reject(res.errMessage)
                    }
                })
            })
        },
        async loadData(selectedOptions) {
            const targetOption = selectedOptions[selectedOptions.length - 1];
            targetOption.loading = true;
            let list = await this._queryAreaInfo(selectedOptions[selectedOptions.length - 1].areaId);
            if(selectedOptions.length == 1){
                this.cityList = list;
            }
            if(selectedOptions.length == 2){
                this.areaList = list;
            }
            targetOption.loading = false;
            targetOption.children = list;
            this.options = [...this.options];
        },
    }
}

</script>
<style scoped>
.imgUrl{
    width: 180px;
    height: 100px;
}
.ant-carousel >>> .slick-slide img {
    text-align: center;
    height: 300px;
    line-height: 300px;
    background: #364d79;
    overflow: hidden;
    width: 100%;
}
.ant-carousel >>> .slick-thumb {
  bottom: -15px;
}
.ant-carousel >>> .slick-thumb li {
  width: 60px;
  height: 45px;
}
.ant-carousel >>> .slick-thumb li img {
  width: 100%;
  height: 100%;
  filter: grayscale(100%);
}
.ant-carousel >>> .slick-thumb li.slick-active img {
  filter: grayscale(0%);
}
</style>